﻿using Masuit.Tools.Systems;
using SqlSugar;

namespace SimpleX
{
    /// <summary>
    /// 分布式自增Id & 雪花ID
    /// </summary>
    public static class IDUtils
    {
        /// <summary>
        /// 获取主键ID
        /// </summary>
        /// <returns></returns>
        public static string GetId()
        {
            return SnowFlakeNew.LongId.ToString();
        }

        public static long NextTableId<T>(T table)
        {
            // 获取表名
            var tableName = table
                .GetType()
                .GetCustomAttributes(typeof(SugarTable), false)
                .OfType<SugarTable>()
                .FirstOrDefault()
                ?.TableName;

            //NextId
            return App.ServiceProvider.GetService<SimpleX.Cache.ICacheService>()
                .Increment($"IDUtils:NextId:{tableName.ToUpper()}", 1);
        }

        /// <summary>
        /// 申请单号(格式:BillType+YYYYMMDD+5位流水号)
        /// </summary>
        /// <param name="billType"></param>
        /// <returns></returns>
        public static string CreateAssetApplayBillNumber(string billType)
        {
            var ymd = $"{DateTime.Now:yyyyMMdd}";
            var nextId = App.ServiceProvider.GetService<SimpleX.Cache.ICacheService>()
                .Increment($"IDUtils:BillNumber:Apply{billType.ToUpper()}:{ymd}", 1);
            return $"{billType}{ymd}{nextId.ToString().PadLeft(5, '0')}";
        }

        /// <summary>
        /// 项目版本号
        /// </summary>
        /// <param name="projectId"></param>
        /// <returns></returns>
        public static string CreateVersion(string projectId)
        {
            var nextId = App.ServiceProvider.GetService<SimpleX.Cache.ICacheService>()
                .Increment($"IDUtils:VersionNumber:{projectId.ToUpper()}", 1);

            double versionNumber = 0.9 + Math.Floor(nextId / 10.0) + (nextId % 10) / 10.0;
            return $"{versionNumber:F1}";
        }
    }
}